package com.museum.controller;

import com.museum.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Value("${file.upload-dir}")
    private String uploadDir;
    
    // 允许的文件类型
    private static final String[] ALLOWED_FILE_TYPES = {
            "image/jpeg", "image/png", "image/gif", "image/bmp", "image/webp"
    };
    
    // 最大文件大小 (5MB)
    private static final long MAX_FILE_SIZE = 5 * 1024 * 1024;

    /**
     * 上传文件
     * @param file 上传的文件
     * @return 文件访问URL
     */
    @PostMapping("/upload")
    public Result<Map<String, String>> upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("上传的文件为空");
        }
        
        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !Arrays.asList(ALLOWED_FILE_TYPES).contains(contentType)) {
            return Result.error("不支持的文件类型，仅支持JPEG、PNG、GIF、BMP和WEBP格式的图片");
        }
        
        // 检查文件大小
        if (file.getSize() > MAX_FILE_SIZE) {
            return Result.error("文件大小超过限制，最大5MB");
        }

        try {
            // 确保上传目录存在
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 获取文件后缀
            String originalFilename = file.getOriginalFilename();
            String suffix = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            
            // 生成新文件名
            String fileName = UUID.randomUUID().toString() + suffix;
            Path filePath = uploadPath.resolve(fileName);
            
            // 保存文件
            Files.copy(file.getInputStream(), filePath);
            logger.info("File uploaded successfully: {}", fileName);
            
            // 返回文件访问路径
            Map<String, String> result = new HashMap<>();
            // 返回两种URL格式，以便前端使用
            result.put("url", "/uploads/" + fileName);  // 不带context-path的路径
            result.put("fullUrl", "/api/uploads/" + fileName);  // 带context-path的路径
            result.put("name", fileName);
            result.put("originalName", originalFilename);
            result.put("size", String.valueOf(file.getSize()));
            result.put("type", contentType);
            return Result.success(result);
        } catch (IOException e) {
            logger.error("Failed to upload file", e);
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 获取上传目录配置信息（仅用于调试）
     * @return 目录路径信息
     */
    @GetMapping("/info")
    public Result<Map<String, String>> getFileInfo() {
        Map<String, String> info = new HashMap<>();
        try {
            File dir = new File(uploadDir);
            // 确保目录存在
            if (!dir.exists()) {
                dir.mkdirs();
            }
            info.put("configuredPath", uploadDir);
            info.put("absolutePath", dir.getAbsolutePath());
            info.put("exists", String.valueOf(dir.exists()));
            info.put("canRead", String.valueOf(dir.canRead()));
            info.put("canWrite", String.valueOf(dir.canWrite()));
            info.put("files", String.valueOf(dir.listFiles() != null ? dir.listFiles().length : 0));
            logger.info("File directory info: {}", info);
            return Result.success(info);
        } catch (Exception e) {
            logger.error("Error getting file directory info", e);
            info.put("error", e.getMessage());
            return Result.success(info);
        }
    }

    /**
     * 获取上传的文件列表（仅用于调试）
     * @param limit 最大返回数量
     * @return 文件列表
     */
    @GetMapping("/list")
    public Result<List<Map<String, String>>> listFiles(@RequestParam(defaultValue = "10") int limit) {
        List<Map<String, String>> files = new ArrayList<>();
        try {
            File dir = new File(uploadDir);
            if (!dir.exists() || !dir.isDirectory()) {
                return Result.success(files);
            }
            
            File[] fileList = dir.listFiles();
            if (fileList == null) {
                return Result.success(files);
            }
            
            int count = 0;
            for (File file : fileList) {
                if (count >= limit) break;
                if (file.isFile()) {
                    Map<String, String> fileInfo = new HashMap<>();
                    fileInfo.put("name", file.getName());
                    fileInfo.put("size", String.valueOf(file.length()));
                    fileInfo.put("path", file.getAbsolutePath());
                    fileInfo.put("url", "/uploads/" + file.getName());
                    files.add(fileInfo);
                    count++;
                }
            }
            return Result.success(files);
        } catch (Exception e) {
            logger.error("Error listing files", e);
            return Result.error("Error listing files: " + e.getMessage());
        }
    }
} 